/***************************************************
This file takes all the graduates in the all_students file,
which have been flagged, and extracts when they were enrolled 
***************************************************/


proc sort data=INPUTS.pseo_tx_thecb_2000_2019_enr_qpik out=qpik ;
	by dqb_source_id ; 
run;

proc sort data=INPUTS.pseo_tx_thecb_2000_2019_enr_rsch out=rsch ;
	by dqb_source_id ; 
run;

data enrollment (keep = pik degcip_2dig opeid  credithours  
				 year quarter state cte_flag deglevl_code )
    /view=enrollment;
    
    merge rsch (in=a 
					rename=(enryear=year 
							enrtotsch = credithours)) 
          qpik (in=b rename=(qpik_ssn = pik)) ;
    by dqb_source_id ; 

	state = '48' ; 

	opeid = substr(opeid,3,6)||'00' ;
	deglevl_code = enrlev ;
	
    /* need to add qtimes */
		
	if enrsem = 1 then quarter = 4 ;
	if enrsem = 2 then quarter = 2 ; 
	if enrsem = 3 then quarter = 3 ;
	if enrsem = 4 then quarter = 3 ; 
	degcip_2dig = substr(enrcip,1,2) ;
    
    if year>=2001 & deglevl_code in ('01','02','03','04') ;
	if enrsem = 2 then do ; 
		output ;
		quarter = 1 ; 
		output ; 
	end ;
	else output ; 
run;

proc freq data=enrollment ;
    tables quarter year / missing; 
run;

proc sort data=enrollment out=enrollmentsort; 
    by pik opeid deglevl_code year quarter; 
run;
    
proc sort data=OUTPUTS.all_students_thecb (where=(pik ne '')) out=all ; 
    by pik opeid ; 
run; 

data OUTPUTS.enrollment_long_thecb; 
    merge enrollmentsort (in=a) all (in=b drop=year quarter) ;
    by pik opeid ; 
    
    if b ; 
    if pik ne '' ;
    if year = . then year = year_grad; 
    if quarter = . then quarter = quarter_grad ; 
    enroll= a ; 
    qtime = %qtime(year,quarter,location=datastep) ;
run;

proc sort data=OUTPUTS.enrollment_long_thecb ;
	by pik opeid deglevl_code degcip_2dig qtime ; 
run;

proc sort data=OUTPUTS.enrollment_long_thecb out=sample_flag ; 
    by pik opeid ; 
run;


/****************************
Making enrollment wide file
*****************************/

data OUTPUTS.enrollment_wide_thecb (keep = pik opeid degcip_2dig credithours 
										flag_cte graduate enr61-enr138 state deglevl_code
										qtime_grad)  ;
	set sample_flag ;
	by pik opeid ;
	
	retain enr21-enr138 ;
	array enr{21:138} enr21-enr138;  
	if qtime <= 138 ; 
	if first.opeid then do ; 
        do i = 21 to 138 ; 
            enr{i} = 0 ; 
        end;
    end;
         
    enr{qtime} = enroll ;  
            
    if last.pik then output ; 
run;

proc sort data=OUTPUTS.enrollment_wide_thecb ;
	by pik opeid deglevl_code degcip_2dig ; 
run;
